package com.sanjiahantang.youjiaclient.module.cases.views.impl;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.util.Pair;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.sanjiahantang.uilibrary.R;
import com.sanjiahantang.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.uilibrary.utils.DensityUtils;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.uilibrary.views.MyListView;
import com.sanjiahantang.uilibrary.views.ObservableScrollView;
import com.sanjiahantang.uilibrary.views.supervideo.MediaController;
import com.sanjiahantang.uilibrary.views.supervideo.SuperVideoPlayer;
import com.sanjiahantang.youjiaclient.base.BaseMvpActivity;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.config.StaticValue;
import com.sanjiahantang.youjiaclient.module.cases.beans.CaseBean;
import com.sanjiahantang.youjiaclient.module.cases.presenters.CasePresenter;
import com.sanjiahantang.youjiaclient.module.cases.views.CaseView;
import com.sanjiahantang.youjiaclient.module.decorate.views.impl.DecorateFormActivity;
import com.sanjiahantang.youjiaclient.module.login.views.impl.LoginActivity;
import com.sanjiahantang.youjiaclient.umengshare.UmengShareManager;
import com.sanjiahantang.youjiaclient.utils.FileUtils;
import com.sanjiahantang.youjiaclient.videoplay.VideoPlayActivity;
import com.sockect3d.Vedio_Activity;
import com.squareup.picasso.Picasso;


/**
 * Created by zy on 2017/8/16.
 * 案例详情
 */

public class CaseDetailActivity extends BaseMvpActivity<CaseView, CasePresenter> implements CaseView, View.OnClickListener, ObservableScrollView.OnScrollChangedListener {
    private CaseDetailActivity $this;
    private SuperVideoPlayer mSuperVideoPlayer;
    private View mPlayBtnView, inc, flVideo, flFavorite,txt3D;
    private ObservableScrollView svMainContent;
    private TextView title, txtRoomType, txtDesignerName;
    private ImageView ivHeader, ivGoOfTitle, ivFavoriteOfTitle, ivGo, ivFavorite, ivDesignerPhoto;
    private MyListView lvInfo;
    private View rlDesigner, rlBack;
    private View containPanel, rlElse;
    private String videoUrl = null;
    private CaseBean.Detail caseDetail;
    private int isCollected = 0;
    private String roamId = null;
    int id;

    @Override
    public CasePresenter initPresenter() {
        return new CasePresenter();
    }

    @Override
    public void initView() {
        setContentView(R.layout.activity_case_detail);
        $this = this;
        mSuperVideoPlayer = (SuperVideoPlayer) findViewById(R.id.video_player_item_1);
        mPlayBtnView = findViewById(R.id.play_btn);

        inc = findViewById(R.id.inc);
        findViewById(R.id.fl_Left).setOnClickListener(this);
        rlBack = findViewById(R.id.rlBack);
        txt3D = findViewById(R.id.txt3D);
        flVideo = findViewById(R.id.mainTitle);
        svMainContent = (ObservableScrollView) findViewById(R.id.scroller);
        title = (TextView) findViewById(R.id.title);
        ivHeader = (ImageView) findViewById(R.id.ivHeader);
        containPanel = findViewById(R.id.contentPanel);
        rlElse = findViewById(R.id.rlElse);
        txtRoomType = (TextView) findViewById(R.id.txtRoomType);
        txtDesignerName = (TextView) findViewById(R.id.txtDesignerName);
        ivGoOfTitle = (ImageView) findViewById(R.id.icon1);
        ivGoOfTitle.setOnClickListener(this);
        ivFavoriteOfTitle = (ImageView) findViewById(R.id.icon2);
        ivFavoriteOfTitle.setOnClickListener(this);
        ivGo = (ImageView) findViewById(R.id.ivGo);
        ivGo.setOnClickListener(this);
        ivFavorite = (ImageView) findViewById(R.id.ivFavorite);
        lvInfo = (MyListView) findViewById(R.id.lvInfo);
        ivDesignerPhoto = (ImageView) findViewById(R.id.ivDesignerPhoto);
        findViewById(R.id.flFavorite).setOnClickListener(this);
        findViewById(R.id.play_btn2).setOnClickListener(this);
        txt3D.setOnClickListener(this);

        int type = getIntent().getIntExtra(KEY_TYPE,0);
        TextView meZX = (TextView) findViewById(R.id.meZX);
        meZX.setOnClickListener(this);
        meZX.setText("我要装修");
        if (type == TYPE_DESIGNER){
            meZX.setVisibility(View.INVISIBLE);
        }

        id = getIntent().getIntExtra(KEY_ID, 0);
        if (id > 0) {
            presenter.setDetailCallBack(new DetailCallBack() {

                @Override
                public void loadData(CaseBean.Detail detail) {
                    if (detail == null) return;
                    txtRoomType.setText(detail.getDoor() + " , "
                            + detail.getStyle() + " , "
                            + detail.getAcreage() + "㎡");
                    txtDesignerName.setText(detail.getUserName());
                    if (TextUtils.isEmpty(detail.getRoamId())){
                        txt3D.setVisibility(View.GONE);
                        roamId = null;
                    }else{
                        txt3D.setVisibility(View.VISIBLE);
                        roamId = detail.getRoamId();
                    }
                    Picasso.with($this).load(FileUtils.rePath(detail.getHeadImg())).placeholder(R.drawable.i_head_default).into(ivDesignerPhoto);
                    Picasso.with($this).load(FileUtils.rePath(detail.getUrlDefault())).placeholder(R.drawable.i_match).into(ivHeader);
                    videoUrl = detail.getIndexVideo();
//                    videoUrl = "http://city24.live-earth.cn:7483/24City/WorksVSP/Video&2018.04.04-19.08.18_1868617344.mp4";
                    caseDetail = detail;

                    if (detail.getState() == 1) {
                        ivFavoriteOfTitle.setImageResource(R.drawable.i_heart_red_on);
                        ivFavorite.setImageResource(R.drawable.i_heart_red_on);
                    } else {
                        ivFavoriteOfTitle.setImageResource(R.drawable.i_heart_black);
                        ivFavorite.setImageResource(R.drawable.i_heart_white);
                    }
                    isCollected = detail.getState();

                    if (!TextUtils.isEmpty(videoUrl)){
                        Bitmap bitmap = null;
                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.FROYO) {
                            bitmap = ThumbnailUtils.createVideoThumbnail(videoUrl, MediaStore.Video.Thumbnails.MINI_KIND);
                        }
                        if (bitmap == null){
                            ivHeader.setImageResource(R.drawable.i_match);
                        }else{
                            ivHeader.setImageBitmap(bitmap);
                        }

                        ivHeader.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                play();
                            }
                        });
                    }else{
                        ivHeader.setOnClickListener(null);
                    }
                }

                @Override
                public void initAdapter(QuickAdapter adapter) {
                    lvInfo.setAdapter(adapter);
                }
            });
            presenter.loadCaseById($this, id);
            rlDesigner = findViewById(R.id.rlDesigner);
            rlDesigner.setOnClickListener(this);
            rlBack.setOnClickListener(this);
        } else {
            Utils.showToast($this, "很抱歉，案例找不到了~");
            finish();
        }

    }

    @Override
    public void initData() {
        mPlayBtnView.setOnClickListener(this);
        mSuperVideoPlayer.setVideoPlayCallback(mVideoPlayCallback);
        inc.setVisibility(View.GONE);
        svMainContent.setOnScrollChangedListener(this);
        title.setText("案例详情");
    }

    @Override
    public void onBackPressed() {
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            this.getResources().getConfiguration().orientation = Configuration.ORIENTATION_PORTRAIT;
            mVideoPlayCallback.onSwitchPageType();
            return;
        }
        super.onBackPressed();

    }

    @Override
    public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) {

        if (Utils.checkIsVisible(this, rlBack)) {
            showTitleView(View.GONE);
        } else {
            showTitleView(View.VISIBLE);
            if (Utils.checkIsVisible(this, rlElse)) {
                ivGoOfTitle.setVisibility(View.GONE);
                ivFavoriteOfTitle.setVisibility(View.GONE);
            } else {
                ivGoOfTitle.setVisibility(View.VISIBLE);
                ivFavoriteOfTitle.setVisibility(View.VISIBLE);
            }

        }
    }

    private void showTitleView(int state) {
        inc.setVisibility(state);
        ivGoOfTitle.setVisibility(state);
        ivFavoriteOfTitle.setVisibility(state);
    }


    @Override
    public void showProgress() {
        super.showProgress($this);
    }

    /**
     * 播放器的回调函数
     */
    private SuperVideoPlayer.VideoPlayCallbackImpl mVideoPlayCallback = new SuperVideoPlayer.VideoPlayCallbackImpl() {
        /**
         * 播放器关闭按钮回调
         */
        @Override
        public void onCloseVideo() {
            mSuperVideoPlayer.close();//关闭VideoView
            mPlayBtnView.setVisibility(View.VISIBLE);
            mSuperVideoPlayer.setVisibility(View.GONE);
            resetPageToPortrait();
        }

        /**
         * 播放器横竖屏切换回调
         */
        @Override
        public void onSwitchPageType() {
            if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                mSuperVideoPlayer.setPageType(MediaController.PageType.SHRINK);
                containPanel.setVisibility(View.VISIBLE);
                rlElse.setVisibility(View.VISIBLE);
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                mSuperVideoPlayer.setPageType(MediaController.PageType.EXPAND);
                containPanel.setVisibility(View.GONE);
                rlElse.setVisibility(View.GONE);
            }
        }

        /**
         * 播放完成回调
         */
        @Override
        public void onPlayFinish() {

        }
    };

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.rlDesigner:
                if (caseDetail != null) {
                    startActivity(new Intent($this, DesignerDetailActivity.class)
                            .putExtra(KEY_PHONE, caseDetail.getPhone())
                            .putExtra(KEY_ID, caseDetail.getId())
                    );
                }

                break;
            case R.id.rlBack:
            case R.id.fl_Left:
                finish();
                break;
            default:
                if (videoUrl == null) {
                    Utils.showToast($this, "无法加载该视频");
                    return;
                }
                mPlayBtnView.setVisibility(View.GONE);
                mSuperVideoPlayer.setVisibility(View.VISIBLE);
                mSuperVideoPlayer.setAutoHideController(false);
                Uri uri = Uri.parse(videoUrl);
                mSuperVideoPlayer.loadAndPlay(uri, 0);
                break;
            case R.id.icon1:
                if (caseDetail != null && caseDetail.getId() != 0){
                    UmengShareManager.share(this,
                            getResources().getString(R.string.app_share_title),
                            getResources().getString(R.string.app_share_content),
                            "?id=" + caseDetail.getId());
                }else{
                    Utils.showToast($this,"分享失败");
                }
                break;
            case R.id.ivGo:
                if (caseDetail != null && caseDetail.getId() != 0){
                    UmengShareManager.share(this,
                            getResources().getString(R.string.app_share_title),
                            getResources().getString(R.string.app_share_content),
                            "?id=" + caseDetail.getId());
                }else{
                    Utils.showToast($this,"分享失败");
                }
                break;
            case R.id.flFavorite:case R.id.icon2:
                if (TextUtils.isEmpty(ConfigValue.DATA_KEY)) {
                    LoginActivity.logout($this);
                    return;
                }
                if (isCollected == 1) {
                    isCollected = 0;
                    ivFavorite.setImageResource(R.drawable.i_heart_white);
                    ivFavoriteOfTitle.setImageResource(R.drawable.i_heart_black);
                    presenter.deleteCollectInfo(this, id);
                } else {
                    isCollected = 1;
                    ivFavorite.setImageResource(R.drawable.i_heart_red_on);
                    ivFavoriteOfTitle.setImageResource(R.drawable.i_heart_red_on);
                    presenter.addCollectInfo(this, id);
                }


                break;

            case R.id.meZX:
                startActivity(new Intent(this, DecorateFormActivity.class));
                break;
            case R.id.play_btn2:
                if (videoUrl == null) {
                    Utils.showToast($this, "无法加载该视频");
                    return;
                }

                Intent intent = new Intent(this, VideoPlayActivity.class);
                intent.putExtra(VideoPlayActivity.TRANSITION, true);
                intent.putExtra(StaticValue.VIDEO_URL, videoUrl);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    Pair pair = new Pair<>(view, VideoPlayActivity.IMG_TRANSITION);
                    ActivityOptionsCompat activityOptions =
                            ActivityOptionsCompat.makeSceneTransitionAnimation(this, pair);
                    ActivityCompat.startActivity(this, intent, activityOptions.toBundle());
                } else {
                    startActivity(intent);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
                        overridePendingTransition(R.anim.abc_fade_in, R.anim.abc_fade_out);
                    }
                }
                break;
            case R.id.txt3D:
                if(TextUtils.isEmpty(roamId)){
                    Utils.showToast($this,"没有3D漫游方案");
                }else{
                    Vedio_Activity.startActivity($this,roamId);
                }
                break;
        }

    }

    public void play(){
        Intent intent = new Intent(this, VideoPlayActivity.class);
        intent.putExtra(VideoPlayActivity.TRANSITION, true);
        intent.putExtra(StaticValue.VIDEO_URL, videoUrl);
        startActivity(intent);
    }

    /***
     * 旋转屏幕之后回调
     *
     * @param newConfig newConfig
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (null == mSuperVideoPlayer) return;
        /***
         * 根据屏幕方向重新设置播放器的大小
         */
        if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                    WindowManager.LayoutParams.FLAG_FULLSCREEN);

            getWindow().getDecorView().invalidate();
            float height = DensityUtils.getWidthInPx(this);
            float width = DensityUtils.getHeightInPx(this);
            mSuperVideoPlayer.getLayoutParams().height = (int) width;
            mSuperVideoPlayer.getLayoutParams().width = (int) height;
        } else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            final WindowManager.LayoutParams attrs = getWindow().getAttributes();
//            attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);

            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

            getWindow().setAttributes(attrs);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            float width = DensityUtils.getWidthInPx(this);
            float height = DensityUtils.dp2px(this, 200.f);
            mSuperVideoPlayer.getLayoutParams().height = (int) height;
            mSuperVideoPlayer.getLayoutParams().width = (int) width;
        }
    }

    /***
     * 恢复屏幕至竖屏
     */
    private void resetPageToPortrait() {
        if (getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            mSuperVideoPlayer.setPageType(MediaController.PageType.SHRINK);
        }
    }
}

